package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.config.MinioConfig;
import com.macro.mall.tiny.service.FileService;
import com.macro.mall.tiny.util.MinioUtil;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author huangzhen
 * @date 2021/11/3 16:40
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioUtil minioUtil;

    @Override
    public String uploadFile(MultipartFile file, String bucketName) {
        try {
            //获取存储桶名
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            //判断存储桶是否存在
            if (!minioUtil.bucketExists(bucketName)) {
                minioUtil.makeBucket(bucketName);
            }
            String fileName = file.getOriginalFilename();
            // 这里有需要再修改，现在修改了原有文件名
            /*String filePath = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));*/
            // 文件格式： 年/月/日/uuid-源文件名
            String filePath = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) +
                    UUID.randomUUID().toString().replaceAll("-", "") + "-" + fileName;
            minioUtil.putObject(bucketName, file, filePath);
            // 生成一个可预览的链接
            // String objectUrl = (String)minioUtil.presignedGetObject(bucketName, filePath, 1200);
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    @Override
    public void download(String filePath, String bucketName, HttpServletResponse response) {
        bucketName=StringUtils.isNotBlank(bucketName) ? bucketName: minioConfig.getBucketName();

        try {
            InputStream object = minioUtil.getObject(bucketName, filePath);

            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();

            String fileName = filePath.substring(filePath.indexOf("-")+1);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            OutputStream outputStream = response.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    @Override
    public void delete(String filePath, String bucketName) {
        bucketName=StringUtils.isNotBlank(bucketName) ? bucketName: minioConfig.getBucketName();
        try {
            minioUtil.removeObject(bucketName, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
